package com.yksj.healthtalk.ui.salon;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.universalimageloader.core.ImageLoader;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.entity.TagEntity;
import com.yksj.healthtalk.entity.UploadImageEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.interestwall.TagChooseActivity;
import com.yksj.healthtalk.utils.ToastUtil;

public class SalonInfoForInterestActivity extends BaseFragmentActivity implements
		OnClickListener, OnItemClickListener {
	private ImageView salonHeader;
	private LinearLayout downLin;
	private EditText name;
	private EditText note;
	private Button backBtn;
	private GridView labelGrid;
	private TagAdapter mAdapter;
	private final int TAG_CHOOSE_REQUESTCODE = 5;
	private ArrayList<TagEntity> tags;
	private ToggleButton releaseSystemMsg;
	private UploadImageEntity entity;
	private TagEntity tagEntity;
	private Set<String> set = new TreeSet<String>();
	private ImageLoader mImageLoader;

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		setContentView(R.layout.salon_info_interest);
		initWidget();
		initData();
	}

	private void initData() {
		Intent intent = getIntent();
		if (intent.hasExtra("entity")) {
			entity = intent.getExtras().getParcelable("entity");
		} else {
			entity = new UploadImageEntity();
		}
		// 沙龙头像
		// intent.putExtra("pic_path", mSmallFile.getAbsolutePath().toString());
		if (intent.hasExtra("pic_path")) {
			String path = intent.getExtras().getString("pic_path");
			mImageLoader = ImageLoader.getInstance();
			mImageLoader.displayImage("4",Uri.fromFile(new File(path)).toString(),
					salonHeader);
		}

		name.setText(entity.getPicname());
		note.setText(entity.getPicdesc());

		tags = new ArrayList<TagEntity>();
		tags = (ArrayList<TagEntity>) entity.getInfos();
		mAdapter = new TagAdapter(this);
		mAdapter.entities = tags;
		tagEntity = new TagEntity("", "+");
		mAdapter.entities.add(mAdapter.entities.size(), tagEntity);
		labelGrid.setAdapter(mAdapter);
	}

	private void initWidget() {
		backBtn = (Button) findViewById(R.id.title_back);
		downLin = (LinearLayout) findViewById(R.id.downLin);
		salonHeader = (ImageView) findViewById(R.id.salon_icon);
		name = (EditText) findViewById(R.id.salon_name);
		note = (EditText) findViewById(R.id.miaoshu);
		labelGrid = (GridView) findViewById(R.id.label_gv);
		releaseSystemMsg = (ToggleButton) findViewById(R.id.info_salon_toggleBtn);
		downLin.setOnClickListener(this);
		backBtn.setOnClickListener(this);
		labelGrid.setOnItemClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.downLin:
			modifySalonInfo();
			break;
		default:
			break;
		}
	}

	/**
	 * 修改沙龙
	 */
	private void modifySalonInfo() {
		HttpRestClient.doHttpUpdateInterestGroup(entity.getPicId(), name
				.getText().toString().trim(), note.getText().toString().trim(),
				buildInfoLayId(), buildUpperLayId(),
				SmartFoxClient.getLoginUserId(), "Y",
				releaseSystemMsg.isChecked() ? "1" : "0",
				new AsyncHttpResponseHandler(this) {
					@Override
					public void onSuccess(int statusCode, String content) {
						if (!content.contains("error_message")) {
							ToastUtil.showShort(getApplicationContext(), "修改成功");
							finish();
						} else{
							ToastUtil.showShort(getApplicationContext(), "修改失败");
						}
						super.onSuccess(statusCode, content);
					}
				});

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		
	}

	private class TagAdapter extends BaseAdapter {
		List<TagEntity> entities = new ArrayList<TagEntity>();
		final LayoutInflater mInflater;

		public TagAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return entities.size();
		}

		@Override
		public TagEntity getItem(int position) {
			return entities.get(position);
		}

		public void notifyAdapter() {
			if (entities.contains(tagEntity)) {
				entities.remove(tagEntity);
			}
			entities.add(entities.size(), tagEntity);
			notifyDataSetChanged();
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView textView;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.salon_info_type_item,
						null);
				textView = (TextView) convertView.findViewById(R.id.info_type);
				convertView.setTag(textView);
			} else {
				textView = (TextView) convertView.getTag();
			}
			if (position == entities.size() - 1) {
				textView.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						onChooseTag();
					}
				});
			} else {
				textView.setOnClickListener(null);
			}
			textView.setText(getItem(position).getName());
			return convertView;
		}
	}

	public void onChooseTag() {
		Intent intent = new Intent(this, TagChooseActivity.class);
		intent.putExtra("resid", R.xml.interestwall_class_store);
		if (tags != null && tags.size() > 0) {
			if (tags.size() >= 1
					&& tags.get(tags.size() - 1).getName().equals("+")) {
				tags.remove(tags.size() - 1);
			}
			intent.putParcelableArrayListExtra("tags", tags);
		}
		startActivityForResult(intent, TAG_CHOOSE_REQUESTCODE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case TAG_CHOOSE_REQUESTCODE:
			if (resultCode != Activity.RESULT_OK)
				return;
			tags = data.getParcelableArrayListExtra("tags");
			if (tags != null) {
				List<TagEntity> list = mAdapter.entities;
				list.clear();
				list.addAll(tags);
				list.add(tagEntity);
			}
			mAdapter.notifyAdapter();
			break;
		}
	}

	/**
	 * 字符串组合 分类id 以逗号分隔开
	 */
	public String buildInfoLayId() {
		String infoId = "";
		if (tags != null && tags.size() > 0) {
			for (int i = 0; i < tags.size(); i++) {
				TagEntity entity = tags.get(i);
				if (!TextUtils.isEmpty(entity.getId())) {
					infoId = infoId + entity.getId() + ",";
				}
			}
		}
		return infoId.substring(0, infoId.lastIndexOf(","));
	}

	/**
	 * 大类id以逗号隔开 去重复
	 * 
	 * @return
	 */
	public String buildUpperLayId() {
		String upperId = "";
		if (tags != null && tags.size() > 0) {
			for (int i = 0; i < tags.size(); i++) {
				TagEntity entity = tags.get(i);
				if (!TextUtils.isEmpty(entity.getUpperId())) {
					set.add(entity.getUpperId());

				}
			}
			Iterator<String> iterator = set.iterator();
			while (iterator.hasNext()) {
				upperId = upperId + iterator.next() + ",";
			}
			set.clear();
		}
		return upperId.substring(0, upperId.lastIndexOf(","));
	}

}
